﻿using DTcms.Common;
using DTcms.Web.Mvc.UI;
using System;
using System.Text;
using System.Web.Mvc;

namespace DTcms.Web.Mvc.Areas.Admin.Controllers
{
    public class UnitController: Controller
    {
        protected internal Model.siteconfig siteConfig= new BLL.siteconfig().loadConfig();
        
        /// <summary>
        /// 在执行Active之后执行
        /// </summary>
        /// <param name="filterContext"></param>
        protected virtual void AfterOnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
        }

        /// <summary>
        /// 在执行Active之前执行
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {

        }

        /// <summary>
        /// 跳转错误页面
        /// </summary>
        /// <param name="filterContext"></param>
        private void GoError(ActionExecutingContext filterContext)
        {
            //
        }

        /// <summary>
        /// 当前的域名地址
        /// </summary>
        /// <returns></returns>
        public string LocalHost
        {
            get { return "http://" + Request.Url.Host; }
        }

        #region 全局参数获取 MobileRS

        /// <summary>
        /// 请求字符
        /// </summary>
        /// <param name="filterContext"></param>
        /// <param name="name"></param>
        /// <param name="defvalue"></param>
        /// <returns></returns>
        public string MobileRS(ActionExecutingContext filterContext, string name, string defvalue = "")
        {
            try
            {
                if (filterContext.HttpContext.Request[name] != null)
                {
                    return filterContext.HttpContext.Request[name];
                }
                else
                {
                    return defvalue;
                }
            }
            catch (Exception)
            {
                return defvalue;
                throw;
            }
        }

        /// <summary>
        /// 请求整型
        /// </summary>
        /// <param name="filterContext"></param>
        /// <param name="name"></param>
        /// <param name="defvalue"></param>
        /// <returns></returns>
        public int MobileRI(ActionExecutingContext filterContext, string name, int defvalue = -1)
        {
            try
            {
                return Convert.ToInt32(MobileRS(filterContext, name));
            }
            catch (Exception)
            {
                return defvalue;
                throw;
            }
        }

        /// <summary>
        /// 请求日期
        /// </summary>
        /// <param name="filterContext"></param>
        /// <param name="name"></param>
        /// <param name="defvalue"></param>
        /// <returns></returns>
        public DateTime MobileRD(ActionExecutingContext filterContext, string name, DateTime defvalue = new DateTime())
        {
            try
            {
                return Convert.ToDateTime(MobileRS(filterContext, name));
            }
            catch (Exception)
            {
                return defvalue;
                throw;
            }
        }

        /// <summary>
        /// 请求布尔
        /// </summary>
        /// <param name="filterContext"></param>
        /// <param name="name"></param>
        /// <param name="defvalue"></param>
        /// <returns></returns>
        public bool MobileRB(ActionExecutingContext filterContext, string name, bool defvalue = false)
        {
            try
            {
                return Convert.ToBoolean(MobileRS(filterContext, name));
            }
            catch (Exception)
            {
                return defvalue;
                throw;
            }
        }

        /// <summary>
        /// 是否为Ajax请求
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        public bool IsAjaxRequest(ActionExecutingContext filterContext)
        {
            return filterContext.RequestContext.HttpContext.Request.IsAjaxRequest();
        }

        #endregion

        #region 请求参数赋值函数 RS

        /// <summary>
        /// 请求字符
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defvalue"></param>
        /// <returns></returns>
        public string RS(string name, string defvalue = "")
        {
            try
            {
                if (Request[name] != null)
                {
                    return Request[name];
                }
                else
                {
                    return defvalue;
                }
            }
            catch (Exception)
            {
                return defvalue;
                throw;
            }
        }

        /// <summary>
        /// 请求整型
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defvalue"></param>
        /// <returns></returns>
        public int RI(string name, int defvalue = -1)
        {
            try
            {
                return Convert.ToInt32(RS(name));
            }
            catch (Exception)
            {
                return defvalue;
                throw;
            }
        }

        /// <summary>
        /// 请求浮点数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defvalue"></param>
        /// <returns></returns>
        public Double RF(string name, Double defvalue = 0.0)
        {
            try
            {
                return Convert.ToDouble(RS(name));
            }
            catch (Exception)
            {
                return defvalue;
                throw;
            }
        }

        /// <summary>
        /// 请求日期
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defvalue"></param>
        /// <returns></returns>
        public DateTime RD(string name, DateTime defvalue = new DateTime())
        {
            try
            {
                return Convert.ToDateTime(RS(name));
            }
            catch (Exception)
            {
                return defvalue;
                throw;
            }
        }

        /// <summary>
        /// 请求布尔
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defvalue"></param>
        /// <returns></returns>
        public bool RB(string name, bool defvalue = false)
        {
            try
            {
                return Convert.ToBoolean(RS(name));
            }
            catch (Exception)
            {
                return defvalue;
                throw;
            }
        }

        /// <summary>
        /// 路由ID值
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defvalue"></param>
        /// <returns></returns>
        public string RDS(string name = "", string defvalue = "")
        {
            try
            {
                if (string.IsNullOrEmpty(name))
                {
                    return RouteData.Values["Id"].ToString();
                }
                else
                {
                    return RouteData.Values[name].ToString();
                }
            }
            catch (Exception)
            {
                return defvalue;
                throw;
            }
        }
        #endregion

        #region 重写JsonResult
        protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)
        {
            return new CustomJsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding };
        }

        public new JsonResult Json(object data, JsonRequestBehavior jsonRequest)
        {
            return new CustomJsonResult { Data = data, JsonRequestBehavior = jsonRequest };
        }

        public new JsonResult Json(object data)
        {
            return new CustomJsonResult { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
        #endregion

        #region 返回操作是否成功
        /// <summary>
        /// 返回javascript提示信息
        /// </summary>
        /// <returns></returns>
        public string WriteJavascript(int status, string msg, string link)
        {
            return "<script language=\"javascript\"   type=\"text/javascript\">if(typeof window.parent.MSGwindowShow !== 'undefined'){parent.window.MSGwindowShow('editsave','" + status + "','" + msg + "','" + link + "','');}else{layer.alert('" + msg + "');window.location.href='" + link + "'; }</script>";
        }

        /// <summary>
        /// 操作成功
        /// </summary>
        /// <returns></returns>
        public ActionResult IsYes()
        {
            return Json(new { status = 1, msg = "操作成功！" });
        }

        /// <summary>
        /// 操作失败
        /// </summary>
        /// <returns></returns>
        public ActionResult IsNo()
        {
            return Json(new { status = 0, msg = "操作失败！" });
        }
        #endregion

        #region 管理员方法
        #region 检查管理员权限
        /// <summary>
        /// 检查管理员权限
        /// </summary>
        /// <param name="nav_name">菜单名称</param>
        /// <param name="action_type">操作类型</param>
        public void ChkAdminLevel(string nav_name, string action_type)
        {
            Model.manager model = GetAdminInfo();
            BLL.manager_role bll = new BLL.manager_role();
            bool result = bll.Exists(model.role_id, nav_name, action_type);

            if (!result)
            {
                string msgbox = "parent.jsdialog(\"错误提示\", \"您没有管理该页面的权限，请勿非法进入！\", \"back\")";
                Response.Write("<script type=\"text/javascript\">" + msgbox + "</script>");
                Response.End();
            }
        }
        #endregion

        #region 取得管理员信息
        /// <summary>
        /// 取得管理员信息
        /// </summary>
        public Model.manager GetAdminInfo()
        {
            if (IsAdminLogin())
            {
                Model.manager model = System.Web.HttpContext.Current.Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
                if (model != null)
                {
                    return model;
                }
            }
            return null;
        }
        #endregion

        #region 判断管理员是否已经登录(解决Session超时问题)
        /// <summary>
        /// 判断管理员是否已经登录(解决Session超时问题)
        /// </summary>
        public bool IsAdminLogin()
        {
            //如果Session为Null
            if (System.Web.HttpContext.Current.Session[DTKeys.SESSION_ADMIN_INFO] != null)
            {
                return true;
            }
            else
            {
                //检查Cookies
                string adminname = Utils.GetCookie("AdminName", "DTcms");
                string adminpwd = Utils.GetCookie("AdminPwd", "DTcms");
                //cookies密码解密
                try
                {
                    //用户名加密
                    adminname = DESEncrypt.Decrypt(adminname, DTKeys.COOKIE_KEY);
                    //密码绑定IP
                    adminpwd = DESEncrypt.Decrypt(adminpwd, DTRequest.GetIP());
                }
                catch
                {
                    return false;
                }
                if (adminname != "" && adminpwd != "")
                {
                    BLL.manager bll = new BLL.manager();
                    Model.manager model = bll.GetModel(adminname, adminpwd);
                    if (model != null)
                    {
                        System.Web.HttpContext.Current.Session[DTKeys.SESSION_ADMIN_INFO] = model;
                        return true;
                    }
                }
            }
            return false;
        }
        #endregion

        #region 写入管理日志
        /// <summary>
        /// 写入管理日志
        /// </summary>
        /// <param name="action_type"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public bool AddAdminLog(string action_type, string remark)
        {
            if (siteConfig.logstatus > 0)
            {
                Model.manager model = GetAdminInfo();
                int newId = new BLL.manager_log().Add(model.id, model.user_name, action_type, remark);
                if (newId > 0)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region 检查管理员权限
        /// <summary>
        /// 检查管理员权限
        /// </summary>
        /// <returns></returns>
        public Model.manager_role GetAdminRole()
        {
            Model.manager model = GetAdminInfo();
            return new BLL.manager_role().GetModel(model.role_id);
        }
        #endregion

        #region 查找匹配的URL
        /// <summary>
        /// 查找匹配的URL
        /// </summary>
        /// <param name="channel_id">频道ID</param>
        /// <param name="call_index">调用名</param>
        /// <param name="id">ID</param>
        /// <returns></returns>
        public string get_url_rewrite(string channel_name, string type, string call_index, int id)
        {
            string querystring = id.ToString();
            if (string.IsNullOrEmpty(channel_name))
            {
                return string.Empty;
            }
            if (!string.IsNullOrEmpty(call_index))
            {
                querystring = call_index;
            }
            BLL.url_rewrite bll = new BLL.url_rewrite();
            Model.url_rewrite model = bll.GetInfo(channel_name, type);
            if (model != null)
            {
                return UrlHelperExtend.linkurl(model.name, querystring);

            }
            return string.Empty;
        }
        #endregion
        #endregion
    }
}